package com.edt.ichannel.utils;

import cc.edt.iceutils2.random.IceRandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 */
public class StringUtils {
    private static Logger logger = LoggerFactory.getLogger(StringUtils.class);

    @Resource(name = "redisTemplate")
    private static long seq = 0L;
    private static Date lastDate;

    /**
     * @return java.lang.String
     * @author 李爽
     * @date 2018/6/1 20:48
     * modidy by sl
     * 获取订单编号 年月日时分秒毫秒+加0-9自增序列+两位随机数
     * 每一毫秒最多 9 个 ，如果一毫秒内请求大于9 则阻塞到下一毫秒获取
     * 不能集群，集群有可能重复
     */
    public static synchronized String ramdomOrderNo() {
        Date date = new Date();
        SimpleDateFormat myFmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        if(lastDate != null && date.getTime()-lastDate.getTime()  == 0){
            seq++;
            if (seq > 9) {
                //阻塞到下一个毫秒,获得新的时间戳
                date = tilNextMillis(lastDate);
                seq = 0;
            }
        }else{
            seq = 0;
        }
        lastDate = date;
        return myFmt.format(date)+seq+IceRandomUtils.randomNumeric(2);
    }

    /**
     * 阻塞到下一个毫秒，直到获得新的时间戳
     */
    private static Date tilNextMillis(Date lastDate) {
        Date date = new Date();
        while (date.getTime() <= lastDate.getTime()) {
            date = new Date();
        }
        return date;
    }



}
